/* Class names */
var RSCROLLER_CLASS = "rscroll";
var LSCROLLER_CLASS = "lscroll";
var SECTIONDATA_CLASS = "section_data";
var NUMBERBANNER_CLASS = "number_banner";
var POPUPCONTAINER_CLASS = "popup_container";
var TOOLTIPCONTAINER_CLASS = "tooltip_container";
var SECTIONGRID_CLASS = "section_grid";

/* Animation speeds */
var NO_ANIMATION = 0;
var FAST_ANIMATION = 500;
var SLOW_ANIMATION = 1000;

/* Global consts */
var minVisibleItems = 3;

window.common = window.common || {};

var classStr = common.classStr;
var noOp = common.noOp;

// Facebook related
var FaceBookInfo = {
	FBAppId : "133899810040381",
	StatusTypes : {
		LOGGED_IN : 0,
		LOGGED_OUT : 1
	},
	CurrentStatus : 0
};

function itemWidth(item) 
{
	var width = item.css("width");
	var lmargin = item.css("margin-left");
	var rmargin = item.css("margin-right");
	
	return parseFloat(width) + parseFloat(lmargin) + parseFloat(rmargin) + 5;
}

function updateScrollers()
{
	var rscroller = $(classStr(RSCROLLER_CLASS));
	var lscroller = $(classStr(LSCROLLER_CLASS));
	
	rscroller.each(function() {
		var parent = $(this).parent();
		var tns = $(classStr(SECTIONDATA_CLASS), parent);
		var count = tns.length;
		var width = count > 0 ? itemWidth(tns) : 0;
		
		var container = $(classStr(SECTIONGRID_CLASS), parent);
		var visible = itemWidth(container) / width;
		
		if (count >= visible)
			$(this).fadeIn(FAST_ANIMATION, noOp);
		
		if (count < visible)
			$(this).fadeOut(FAST_ANIMATION, noOp);
	});
}

function enableScrollers()
{
	var rscroller = $(classStr(RSCROLLER_CLASS));
	var lscroller = $(classStr(LSCROLLER_CLASS));
	
	rscroller.fadeOut(NO_ANIMATION, noOp);
	lscroller.fadeOut(NO_ANIMATION, noOp);
	
	updateScrollers();
	
	$(classStr(LSCROLLER_CLASS)).click(function() {
		var parent = $(this).parent();
		var tns = $(classStr(SECTIONDATA_CLASS), parent);
		var count = tns.length;
		var left = parseFloat(tns.css("left"));
		var width = itemWidth(tns);
		var scroll = left / width;

		++scroll;
		
		tns.animate({
			left: '+=' + width
		}, SLOW_ANIMATION, noOp);

		/* Disable left scroller when we have no items on the left */
		if (scroll == 0) {
			$(this).fadeOut(FAST_ANIMATION, noOp);
		}

		/* If more than 3 items are visible, enable the right scroller */
		var container = $(classStr(SECTIONGRID_CLASS), parent);
		var visible = itemWidth(container) / width;
		
		if (count + scroll > visible)
			$(classStr(RSCROLLER_CLASS), parent).fadeIn(FAST_ANIMATION, noOp);
	});
	
	$(classStr(RSCROLLER_CLASS)).click(function() {
		var parent = $(this).parent();
		var tns = $(classStr(SECTIONDATA_CLASS), parent);
		var count = tns.length;
		var left = parseFloat(tns.css("left"));
		var width = itemWidth(tns);
		var scroll = left / width;

		--scroll;
		
		tns.animate({
			left: '-=' + width
		}, SLOW_ANIMATION, noOp);

		if (scroll == -1) {
			$(classStr(LSCROLLER_CLASS), parent).fadeIn(FAST_ANIMATION, noOp);
		}

		var container = $(classStr(SECTIONGRID_CLASS), parent);
		var visible = itemWidth(container) / width;

		/* Disable the right scroller when we have only 3 items visible */
		if (count + scroll < visible) {
			$(this).fadeOut(FAST_ANIMATION, noOp);
		}
	});
}

function updateCounts()
{
	var banner = $(classStr(NUMBERBANNER_CLASS));
	banner.each(function () {
		var parent = $(this).parent().parent();
		var tns = $(classStr(SECTIONDATA_CLASS), parent);
		var count = tns.length;
		
		$(this).text(count);
	});
}

function addToScrollList(response, sectionType)
{
	var count = response.data.length;
	// Get the 'pointer' to the container that we need
	var target = $("#"+sectionType).children('.section_overflow_grid');
	var elements;
		
	for (var i = 0; i < count; i++) {
		var item = response.data[i];
		var delElement = $('<div>').addClass("red").addClass("close_button");
		var xElement = $('<p>').text("X");
		var imgElement = $('<img>').attr("src", item.thumbNailLink);
		var divElement = $('<div>').addClass(SECTIONDATA_CLASS).attr("id", item.key).attr("name", item.key).css({display:"none"});
		var popupElement = $('<div>').addClass(POPUPCONTAINER_CLASS).css({display: 'none', top: '15px'});
		popupElement.addClass(TOOLTIPCONTAINER_CLASS).attr("id", item.key).attr("name", item.key);

		xElement.appendTo(delElement);
		imgElement.appendTo(divElement);
		delElement.appendTo(divElement);
		divElement.appendTo(target);
		popupElement.appendTo(target);
		
		// Add a 'mouseover' descriptor text
		var header = $('<div>').text(item.title + "  (" + item.year + ")");
		
		var cast = item.actors;
		var index = cast.indexOf(",");
		index = cast.indexOf(",", index + 1);
		index = cast.indexOf(",", index + 1);
		cast = cast.substr(0, index);
		
		var dir = item.directors;
		dir = dir.substr(0, dir.indexOf(","));
		
		var metaData = "<table id=\"itemDescriptorTable\">" + 
						"<tr>" +
						"<td class=\"strong\">" + "Cast: " + "</td>" +
						"<td>" + cast + "</td>" +
					 	"</tr>" +
						"<tr>" +
						"<td class=\"strong\">" + "Direction: " + "</td>" +
						"<td>" + dir + "</td>" +
					 	"</tr>" +
						"<tr>" +
						"<td class=\"strong\">" + "Music: " + "</td>" +
						"<td>" + item.musicDirectors + "</td>" +
					 	"</tr>" +					 	
					 	"</table>";
					 	
		popupElement.append(header);
		popupElement.append(metaData);
		
		// Handle the delete operation
		delElement.click(function(event) {
			var dvdDiv = $(this).parent('div');
			var key = dvdDiv.attr("id");			
			
			$.get("/myDvdDelete", {key:key}, function(response) {
				if (response.status == "ok") {
					$(dvdDiv).fadeOut("normal", function() {
						$(this).remove();
						updateCounts();
						updateScrollers();
					});					
				}
				else {					
					showStatusMessage("Item could not be deleted. Server responded with (" + response.status + ")");
				}
			}, "json");
		});
					 	
		// Add a 'mouseover' handler to popup the description about the element added above
		imgElement.mouseenter(function(event) {
			var overflow = 30;
			var parent = $(this).parent('div');
			var position = parent.position();
			var popup = parent.siblings('div.'+POPUPCONTAINER_CLASS+'#'+parent.attr("name"));
			var container = $(this).closest(classStr(SECTIONGRID_CLASS));
			var popupWidth = itemWidth(popup);
			
			if ((position.left + itemWidth(parent) + popupWidth + overflow) < itemWidth(container)) {
				popup.removeClass('popup_right');
				popup.addClass('popup_left');
				popup.css('left', position.left + itemWidth(parent) + overflow);
			}
			else {
				popup.removeClass('popup_left');
				popup.addClass('popup_right');
				popup.css('left', position.left - popupWidth - overflow);
			}
			popup.show();
		});
		
		imgElement.mouseleave(function(event) {
			var parent = $(this).parent('div');
			var popup = parent.siblings('div.'+POPUPCONTAINER_CLASS+'#'+parent.attr("name"));
			
			popup.hide();		
		});
		
		divElement.fadeIn(FAST_ANIMATION, $.noop);
	}
	
	updateCounts();
	updateScrollers();
}

function setupSearch() {
	/* Search button action */
	$(".search_submit").click(function() {
		showStatusMessage("Search is not enabled - please try later");
	});			
}	

function setupMainMenu() {
	$(".user_nav_menu").click(function() {
		var layer = $(".nav_container");
		var list = $("#user_menu");

		if(list.css("display") == "none") {
			list.css("display", "block");
			layer.css("background", "rgb(221, 221, 221)");
			layer.css("-webkit-box-shadow", "0px 1px 2px black");
			layer.css("box-shadow", "0px 1px 2px black");
		} else {
			list.css("display", "none");
			layer.css("background", "");
			layer.css("-webkit-box-shadow", "none");
			layer.css("box-shadow", "none");
		}
	});	
}	

function setupMyItemsSection() {	
	// Set status to 'loading', as this might take a while...
	showStatusMessage("Loading user content...", StatusMessage.STICKY);

	var previewFormScope = $("#newItemPreviewForm");							
	// Store references to the previous fields for quick access
	var previewItemTitle = $("#newItemTitle", previewFormScope)[0];
	var previewItemYear = $("#newItemYear", previewFormScope)[0];
	var previewItemLink = $("#newItemLink", previewFormScope)[0];
	var previewItemActors = $("#newItemActors", previewFormScope)[0];
	var previewItemDirectors = $("#newItemDirectors", previewFormScope)[0];
	var previewItemMusicDirectors = $("#newItemMusicDirectors", previewFormScope)[0];
	var previewItemThumbNail = $("#newItemThumbNail", previewFormScope);
	var previewItemSubmit = $("#newItemSubmit", previewFormScope);
							
	/* Setup callbacks */
	// The main 'Add button' callback
	$("#addItemButton").click(function() {
		previewItemTitle.resetValue();  					
		previewItemYear.resetValue();
		previewItemLink.resetValue();
		previewItemActors.resetValue();
		previewItemDirectors.resetValue();
		previewItemMusicDirectors.resetValue();
		previewItemThumbNail.attr("src", "/thumbs/noImage.png");
		previewItemSubmit.attr('disabled', true);
		showPopup("newItemContainer");
		return false;
	});	
	
	$(".my_items_popup_hide").click(function() {
		hidePopup("newItemContainer");
		return false;
	});
		
	$("#newItemInputForm").submit(function(event) {
		var itemDetailsQuery = {
			type:$("#newItemType", this).val(),
			title:$("#newItemTitle", this)[0].getValue()
		};							   	    
		var responseHandler = function(response) {		
			if (response.status == "ok") {
							
				// Dynamically expand the
				$("#newItemTitle", previewFormScope)[0].setValue(response.data[0].title); 					
				$("#newItemYear", previewFormScope)[0].setValue(response.data[0].year);
				$("#newItemLink", previewFormScope)[0].setValue(response.data[0].imdb);
				$("#newItemActors", previewFormScope)[0].setValue(response.data[0].actors);
				$("#newItemDirectors", previewFormScope)[0].setValue(response.data[0].directors);
				$("#newItemMusicDirectors", previewFormScope)[0].setValue(response.data[0].musicDirectors);
				$("#newItemThumbNail", previewFormScope).attr("src", response.data[0].thumbNailLink);
				$("#newItemSubmit", previewFormScope).removeAttr('disabled');
				showStatusMessage("", StatusMessage.RESET);
			}					
			else {	
				var str = "Predictive search could not happen. Server responded with (" + response.status + ")" 				
				logC(str);
				showStatusMessage(str);
			}
		};
			
		$("#newItemSubmit", previewFormScope).attr('disabled', '');
							   
		logC("entered key -> " + itemDetailsQuery.title);
		
		showStatusMessage("Getting details...", StatusMessage.STICKY);
		
		$.get("/getSimilarDvds", itemDetailsQuery, responseHandler, "json");
		
		return false;
	});
			
	$("#newItemPreviewForm").submit(function() {
		showStatusMessage("Adding movie entry...", StatusMessage.STICKY);

		// TODO: Validate the inputs !!!
		var newItem = {
			type:$('#newItemType', this).val(),
			title:$('#newItemTitle', this)[0].getValue(),
			year:$('#newItemYear', this)[0].getValue(),
			actors:$('#newItemActors', this)[0].getValue(),
			directors:$('#newItemDirectors', this)[0].getValue(),
			musicDirectors:$('#newItemMusicDirectors', this)[0].getValue(),
			imdb:$('#newItemLink', this)[0].getValue(),
			thumbNailLink:$('#newItemThumbNail', this).attr("src")
		};
		
		hidePopup("newItemContainer");
		
		$.post("/myDvdAdd", newItem, function(response) {
			if (response.status == "ok") {
				addToScrollList(response, "myDvdsSection");
				showStatusMessage(null, StatusMessage.RESET);
			}
			else {
				showStatusMessage("Error while adding the new item. Server returned (" + response.status + ")");
			}
		}, "json");
		
		return false;
	});		

	
	// Get the initial list of user DVDs
	
	$.get("/myDvdList", {request:"list"}, function(response) {
			if (response.status == "ok") {
				addToScrollList(response, "myDvdsSection");
				showStatusMessage(null, StatusMessage.RESET);				
			}
			else {
				showStatusMessage("Error while loading the user list. Server returned (" + response.status + ")");
			}
	}, "json");	
}

function setFaceBookStatus(status) {
	switch (status) {
		case FaceBookInfo.StatusTypes.LOGGED_IN:
			logC("You are connected to FB");
			FaceBookInfo.CurrentStatus = status;
			// Current status is logged in. so change the button to logged out	
			$("#friendsFBDiv").empty().html('<a href=\"#\" class=\"button green right\" id="friendFBButton">' +
											' Disconnect from FaceBook ' +
											'</a>');
			$("#friendFBButton").click(function() {
				alert("hello");
				FB.logout();
			});
			break;
		case FaceBookInfo.StatusTypes.LOGGED_OUT:
			logC("You are not connected to FB");
			FaceBookInfo.CurrentStatus = status;
			// Current Status is logged out. So the button should become a login button	
			$("#friendsFBDiv").empty().html('<fb:login-button show-faces="true" width="200"' + 
    										' max-rows="1" perms="user_likes, friends_likes">' +
    										' Connect via FaceBook ' + 
    										'</fb:login-button>');
    		FB.XFBML.parse();
    		break;
    }
}

function setupMyFriendsSection()
{
	// Check if you are logged into FB 
	FB.init({
				appId  : FaceBookInfo.FBAppId,
				status : true, // check login status
				cookie : true, // enable cookies 
				xfbml  : true  // parse XFBML
			});
	FB.Event.subscribe('auth.sessionChange', function(response) {
		logC("subscribe event with response -> " + response.status);
		switch (response.status) {
			case "connected":
				logC("Connected to FB");
				setFaceBookStatus(FaceBookInfo.StatusTypes.LOGGED_IN);
				$("#friendsFBDiv").empty().html('<a href=\"#\" class=\"button green right\" id="friendFBButton">' +
												' Disconnect from FaceBook ' +
												'</a>');
				//getFriendsCollection();
				break;
		}
	});
	FB.getLoginStatus(function(response) {
		if (response.session) {
			// logged in and connected user, someone you know
			// get_friend_likes();
			setFaceBookStatus(FaceBookInfo.StatusTypes.LOGGED_IN);
			//getFriendsCollection();					
		} else {
			
			setFaceBookStatus(FaceBookInfo.StatusTypes.LOGGED_OUT);
  		}
	});
}

function setupMyWishListSection()
{
	
}

$(document).ready(function() {

	// Global ajaxError handler!
	$('body').ajaxError(function(event, xhr, settings, exception) {				   
						   showStatusMessage("Error while getting data from server. Reason (" + exception.description + ")");   	   	
				   	 });
				   	 
	setupSearch();
	setupMainMenu();
	setupMyItemsSection();
	setupMyFriendsSection();
	setupMyWishListSection();
	
	enableScrollers();
	updateCounts();
});
